package ltd.followkba.page;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.kcbsdk.EventHandler;


import ltd.advskin.C;
import ltd.advskin.MSKIN;
import ltd.advskin.base.BasePage;

import ltd.advskin.base.KcTypeListener;
import ltd.advskin.media.PlayStatus;
import ltd.advskin.task.TaskFree;
import ltd.advskin.view.KcBtnImage;
import ltd.advskin.view.KcBtnProgress;
import ltd.advskin.view.KcHeaderView;
import ltd.followkba.MAPP;
import ltd.followkba.MDBS;
import ltd.followkba.R;
import ltd.followkba.W;
import ltd.followkba.task.App32;
import ltd.followkba.task.BDbsAccount;
import ltd.followkba.task.EditUtils;
import ltd.followkba.task.WorksQueue;
import main.MAPI;


import static ltd.advskin.MSKIN.MSTRING;
import static ltd.advskin.MSKIN.MTOAST;
import static main.MAPI.MSLEEP;
import static main.MAPI.mMyUtils;
import static main.MAPI.mMyWorks;

public class LoginManagePage extends BasePage {
    private EditText etAccount, etPassword, etAuthCode;
    private KcBtnImage kbiAccountLogin,kbiPasswordLogin,kbiCodeLogin,kbiAuthCodeLogin;
    private KcBtnProgress kbiSubmit;
    private KcBtnImage kbiLoginDeleteA,kbiLoginDeleteB;
    private TextView tvAlreadyLogin;

//
    private String gsAuthCode;
    private String gsAccountName;
    private String gsPassword;
    private boolean isLogined;
    private String gsResult1;
    private String gsResult2;

    // 所有的页面都接受同样的方式打开LOG
    public static boolean logEnable;
    public void MLOG(String text) {
        MSTRING(MAPI.GET_LOG_NAME(this) + text);
    }

    @Override
    public void onInitView() {                       // 使用者需要继承，初始化页面控件等显示
        setLayout(R.layout.page_manager_login);
        gsAccountName = MSKIN.getMemoryString(W.ManageAccountName, false);
        gsPassword = MSKIN.getMemoryString(W.ManagePassword, false);

        mKcHeaderView = findViewById(R.id.kvhLogin);
        String text = String.format("操作号登录#%s", mMyUtils.getServerNumber());
        mKcHeaderView.setTitle(text, new KcTypeListener() {
            @Override
            public void onMessage(int type){
                switch (type){
                    case KcHeaderView.TYPE_CLICK_LEFT:
                        onFinish();
                        break;
                }
            }
        });
        etAccount = findViewById(R.id.etAccount);
        etPassword = findViewById(R.id.etPassword);
        kbiAccountLogin = findViewById(R.id.kbiAccountLogin);
        kbiPasswordLogin = findViewById(R.id.kbiPasswordLogin);
        kbiCodeLogin = findViewById(R.id.kbiCodeLogin);
        kbiSubmit = findViewById(R.id.btLogin);
        kbiAuthCodeLogin = findViewById(R.id.kbiAuthCodeLogin);
        etAuthCode = findViewById(R.id.etAuthCode);
        tvAlreadyLogin = findViewById(R.id.tvAlreadyLogin);

        kbiLoginDeleteA = (KcBtnImage) findViewById(R.id.kbiLoginDeleteA);
        etAccount.addTextChangedListener(new TextWatcher() {  // 清除账号的内容
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(s.length() > 0 ){ // 判断输入框是否有内容
                    setDelete(false);
                }else{  // 没有内容
                    kbiLoginDeleteA.setVisibility(View.GONE);
                }
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        kbiLoginDeleteB = (KcBtnImage) findViewById(R.id.kbiLoginDeleteB);
        etPassword.addTextChangedListener(new TextWatcher() { // 清除密码的内容
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(s.length() > 0){ // 判断输入框是否有内容
                    setDelete(true);
                }else{  // 没有内容
                    kbiLoginDeleteB.setVisibility(View.GONE);
                }
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        findViewById(R.id.kbtAuthCode).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {   // 换一张
//                mMyManage.fetchAuthCode();
                changAuthCode();
            }
        });
        kbiSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {    // 登录
                gsAccountName = etAccount.getText().toString().trim();
                gsPassword = etPassword.getText().toString().trim();
                gsAuthCode = etAuthCode.getText().toString().trim();
//                gsPassword="d27951479";
                if (MAPI.isEmpty(gsAccountName) || MAPI.isEmpty(gsPassword) || MAPI.isEmpty(gsAuthCode)) {
                    MTOAST("密码、账号或者验证码不能为空");
                    return;
                }
                loginSvr();
            }
        });
        MTOAST("正在检查操作号登录情况，请稍候...", 3000);
    }
    @Override
    public void onInitData(){                                                                       // onInitView结束，开始加载数据
        new Thread(new Runnable() {
            @Override
            public void run() {
                MAPP.setTaskPause(true);
                String loginFlag = MSKIN.getMemoryString(W.ManageLoginFlag, false);
                App32.setUser(loginFlag, (byte) 0);
                isLogined = App32.getGiftAndRank(null, null);
            }
        }).start();

        mMyWorks.setUiEventCallBack(new EventHandler() {
            @Override
            public void onComplete(int methodType, boolean isFail, String message) {
                if (mMyWorks.isEventDataRefresh()){
                    showInfo();
                }
            }
        });
        MLOG(String.format("mMyManage.fetchAuthCode %s(%s)", gsAccountName, gsPassword));
        if (!MAPI.isEmpty(gsAccountName)) {
            etAccount.setText(gsAccountName);
            setDelete(false);
        }
        if (!MAPI.isEmpty(gsPassword)) {
            etPassword.setText(gsPassword);
            setDelete(true);
        }
        MSKIN.setBitmap(C.auth_code, kbiAuthCodeLogin);
        MSKIN.setBitmap(C.account_input, kbiAccountLogin);
        MSKIN.setBitmap(C.password_lock, kbiPasswordLogin);
        MSKIN.setBitmap(C.code_input, kbiCodeLogin);
        changAuthCode();
        if (!isLogined) {
            showInfo();
        }else if (MAPP.mManageAccount != null){
            tvAlreadyLogin.setVisibility(View.VISIBLE);
        }
    }
    @Override
    public void onFinish() {       // 使用者选择性继承，用户按了后退键，不继承就直接关闭了
        MAPP.setTaskPause(false);
        MAPP.gManageLogin = 0;
        setClose();
    }
    private void showInfo(){
        MSKIN.setBitmap(gsResult1, kbiAuthCodeLogin);
    }
    private void loginSvr() {
        gsResult1 = null;
        gsResult2 = null;
        MSKIN.setMemoryString(W.ManageAccountName, gsAccountName, false);
        MSKIN.setMemoryString(W.ManagePassword, gsPassword, false);

        EditUtils editUtils = new EditUtils();
        MAPP.mManageAccount = new BDbsAccount();
        MAPP.mManageAccount.AccountName = gsAccountName;
        MAPP.mManageAccount.WorksType = 32;
        MAPP.mManageAccount.CrcSum5 = editUtils.getCrcSum5(MAPP.mManageAccount.AccountName);
        new TaskFree(null, new TaskFree.Listener() {
            @Override
            public void onMessage(boolean isThread, Object object) {
                if (isThread){
                        MLOG(String.format("KgAppDbsA 登录前%08x(%s)", MAPP.mManageAccount.CrcSum5, MSKIN.getMemoryString(W.ManageLoginFlag, false)));
                        gsResult1 = App32.loginSvr(gsAccountName, gsPassword, gsAuthCode, MAPP.mManageAccount);
                        if ("ok".equals(gsResult1)) {
                            MSKIN.setMemoryString(W.ManageLoginFlag, MAPP.mManageAccount.LoginFlag, false);
                            MDBS.setBDbsAccount(MAPP.mManageAccount);
                            EditUtils editUtils = new EditUtils();
                            MLOG(String.format("KgAppDbsA 登录后%08x(%s)", MAPP.mManageAccount.CrcSum5, MSKIN.getMemoryString(W.ManageLoginFlag, false)));
//                            App32.setUser(MAPP.mManageAccount);
                            String loginFlag = MSKIN.getMemoryString(W.ManageLoginFlag, false);
                            App32.setUser(loginFlag, (byte) 0);
                            gsResult2 = WorksQueue.setKgAppDbs(MAPP.mManageAccount, MDBS.SVR_LOGIN);
                        }

                    return;
                }
                if ("ok".equals(gsResult1) && "ok".equals(gsResult2)){
//                    MSKIN.setMemoryInt(W.ManageUserID, mBDbsAccount.UserID);

                    setPageResult(this);
                    onFinish();
                    MTOAST("成功登录");
                    MLOG(String.format("TaskService 成功登录 %s", MSKIN.getMemoryString(W.ManageLoginFlag, false)));
                }else {
                    String text = String.format("登录出错：%s(%s)", gsResult1, gsResult2);
                    MTOAST(text, 5000);
                }
            }
        });
    }
    private void changAuthCode(){
        new TaskFree(null, new TaskFree.Listener() {
            @Override
            public void onMessage(boolean isThread, Object object) {
                if (isThread){
                    gsResult1 = App32.getAuthCode();
                    if (MAPI.GET_FILE_LENGTH(gsResult1) < 500){
                        MTOAST("图形验证码下载出错");
                    }
                    MLOG(String.format("changAuthCode %s %s", MAPI.GET_FILE_LENGTH(gsResult1), gsResult1));
                    return;
                }
                showInfo();
            }
        });
    }

    private void setDelete(boolean isPassword){
        if (!isPassword){
            kbiLoginDeleteA.setVisibility(View.VISIBLE);
            MSKIN.setBitmap(C.close_only, kbiLoginDeleteA);
            findViewById(R.id.kbiLoginDeleteA).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {  // 清除框内内容
                    etAccount.setText("");
                }
            });
        }else {
            kbiLoginDeleteB.setVisibility(View.VISIBLE);
            MSKIN.setBitmap(C.close_only, kbiLoginDeleteB);
            findViewById(R.id.kbiLoginDeleteB).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {  // 清除框内内容
                    etPassword.setText("");
                }
            });
        }
    }
}
